import Vue from 'vue';
import VueJsonp from 'vue-jsonp';

Vue.use(VueJsonp);


const URLS = {
    home: "https://mce.mogucdn.com/jsonp/multiget/3",
    goodsitem: "https://list.mogujie.com/search",
    typeLeft: "https://mce.mogucdn.com/jsonp/multiget/3",
    typeRight: "https://mce.mogucdn.com/jsonp/get/3",
    keyWords: "https://list.mogujie.com/module/mget",
    detail: "https://rate.mogujie.com/h5/rate/jsonp/x6.rate.ratelist/v1"
}

const error = (error) => {
    if (error.msg) {
        window.$showTip("请求失败,参数错误", 3);
    } else if (error.statusText == "Bad Request") {
        window.$showTip("请求失败,地址错误", 3);
    } else {
        window.$showTip("请求失败,服务器出错", 3);
    }
}

const loadHomeData = function (params = {}) {
    return Vue.jsonp(URLS.home, params)
        .then(({ data, success }) => {
            if (success) {
                return data;
            } else {
                return Promise.reject({
                    msg: "请求失败"
                });
            }
        })
}
const loadGoodsItem = function (params = {}) {
    return Vue.jsonp(URLS.goodsitem, params)
        .then(({ success, result }) => {
            if (success) {
                return result;
            } else {
                return Promise.reject({
                    msg: "请求失败"
                });
            }
        })
}

const loadTypeLeft = function (params = {}) {
    return Vue.jsonp(URLS.typeLeft, params)
        .then(({ success, data }) => {
            if (success) {
                return data;
            } else {
                return Promise.reject({
                    msg: "请求失败"
                });
            }
        })
}

const loadTypeRight = function (params = {}) {
    return Vue.jsonp(URLS.typeRight, params)
        .then(({ success, data }) => {
            if (success) {
                return data;
            } else {
                return Promise.reject({
                    msg: "请求失败"
                });
            }
        })
}

const loadKeyWords = function (params = {}) {
    return Vue.jsonp(URLS.keyWords, params)
        .then(({ success, data }) => {
            if (success) {
                return data;
            } else {
                return Promise.reject({
                    msg: "请求失败"
                });
            }
        })
}

const loadDetail = function (params = {}) {
    return Vue.jsonp(URLS.detail, params)
        .then(({ success, data }) => {
            if (success) {
                return data;
            } else {
                return Promise.reject({
                    msg: "请求失败"
                });
            }
        })
}
export default {
    install: function (Vue) {
        Vue.prototype.$api = {
            loadHomeData,
            loadGoodsItem,
            loadTypeLeft,
            loadTypeRight,
            loadKeyWords,
            loadDetail
        };
        Vue.prototype.$error = error;
    }
}